<template>
	<view class="container">
		<view class="loading" v-if="isLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>
		
		<view class="content" v-else>
			<view class="header">
				<text class="title">发起谈话</text>
				<text class="subtitle">请填写谈话相关信息</text>
			</view>
			
			<view class="form-container">
				<form @submit="submitForm">
					<view class="form-item">
						<view class="label required">谈话对象</view>
						<picker mode="selector" :range="userList" range-key="name" @change="handleUserChange">
							<view class="picker">
								<text :class="{'placeholder': !selectedUser}">{{ selectedUser ? selectedUser.name : '请选择谈话对象' }}</text>
								<text class="arrow">></text>
							</view>
						</picker>
					</view>
					
					<view class="form-item">
						<view class="label required">谈话主题</view>
						<input class="input" v-model="form.talkTitle" placeholder="请输入谈话主题" />
					</view>
					
					<view class="form-item">
						<view class="label required">谈话时间</view>
						<picker mode="multiSelector" :value="timeIndex" :range="timeArray" @change="handleTimeChange" @columnchange="handleTimeColumnChange">
							<view class="picker">
								<text :class="{'placeholder': !form.talkTime}">{{ form.talkTime || '请选择谈话时间' }}</text>
								<text class="arrow">></text>
							</view>
						</picker>
					</view>
					
					<view class="form-item">
						<view class="label required">谈话地点</view>
						<input class="input" v-model="form.talkPlace" placeholder="请输入谈话地点" />
					</view>
					
					<view class="form-item">
						<view class="label required">谈话时长</view>
						<view class="duration-container">
							<view class="duration-btn" @tap="decreaseDuration">-</view>
							<input class="duration-input" type="number" v-model="form.talkDuration" />
							<view class="duration-btn" @tap="increaseDuration">+</view>
							<text class="duration-unit">分钟</text>
						</view>
					</view>
					
					<view class="form-item">
						<view class="label required">谈话摘要</view>
						<textarea class="textarea" v-model="form.talkSummary" placeholder="请输入谈话摘要" maxlength="500" />
						<text class="word-count">{{form.talkSummary.length}}/500</text>
					</view>
					
					<view class="form-item">
						<view class="label">上传附件</view>
						<view class="upload-container">
							<view class="upload-list">
								<view class="upload-item" v-if="selectedFile">
									<view class="file-info">
										<text class="file-name">{{selectedFile.name}}</text>
										<text class="file-size">{{selectedFile.size}}</text>
									</view>
									<view class="delete-btn" @tap="deleteFile">×</view>
								</view>
								<view class="upload-btn" @tap="chooseFile" v-if="!selectedFile">
									<text class="upload-icon">+</text>
									<text class="upload-text">选择文件</text>
								</view>
							</view>
						</view>
					</view>
					
					<button class="submit-btn" form-type="submit" type="primary">提交</button>
				</form>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getDeptUsers,submitTalkInfo,uploadFile } from '@/common/js/api.js'

// 表单数据
const form = reactive({
	talkTitle: '',
	talkTime: '',
	talkPlace: '',
	talkDuration: 30,
	talkSummary: '',
	fileUrl: '',
	userId: ''
})

// 状态数据
const userList = ref([])
const selectedUser = ref(null)
const selectedFile = ref(null)
const timeArray = ref([[], [], []])
const timeIndex = ref([0, 0, 0])
const userId = uni.getStorageSync('userId');

// 加载状态
const isLoading = ref(true)

// 常量数据
const talkTypes = [
	{ label: '入党谈话', value: 'PARTY' },
	{ label: '思想汇报', value: 'THOUGHT' },
	{ label: '其他谈话', value: 'OTHER' }
]

// 初始化时间数组
const initTimeArray = async () => {
	const dates = []
	const now = new Date()
	for (let i = 0; i < 30; i++) {
		const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000)
		dates.push(formatDate(date))
	}
	
	const hours = Array.from({length: 24}, (_, i) => String(i).padStart(2, '0'))
	const minutes = Array.from({length: 60}, (_, i) => String(i).padStart(2, '0'))
	
	timeArray.value = [dates, hours, minutes]
}

// 格式化日期
const formatDate = (date) => {
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	return `${year}-${month}-${day}`
}

// 获取用户列表
const getUserList = async () => {
	try {
		const res = await getDeptUsers(userId);
		if (res.code === 200) {
			userList.value = res.data.sameDeptPeople;
		} else {
			wx.showToast({
				title: '获取用户列表失败',
				icon: 'none'
			})
		}
	} catch (error) {
		wx.showToast({
			title: '获取用户列表失败',
			icon: 'none'
		})
	}
}

// 处理用户选择
const handleUserChange = (e) => {
	const index = e.detail.value
	selectedUser.value = userList.value[index]
	form.userId = selectedUser.value.id
}

// 处理类型选择
const handleTypeChange = (e) => {
	form.talkType = e.detail.value
}

// 处理时间选择
const handleTimeChange = (e) => {
	const [dateIndex, hourIndex, minuteIndex] = e.detail.value
	const date = timeArray.value[0][dateIndex]
	const hour = timeArray.value[1][hourIndex]
	const minute = timeArray.value[2][minuteIndex]
	form.talkTime = `${date} ${hour}:${minute}:00`
}

// 处理时间列变化
const handleTimeColumnChange = (e) => {
	const { column, value } = e.detail
	timeIndex.value[column] = value
}

// 减少时长
const decreaseDuration = () => {
	if (form.talkDuration > 1) {
		form.talkDuration--
	}
}

// 增加时长
const increaseDuration = () => {
	if (form.talkDuration < 480) {
		form.talkDuration++
	}
}

// 选择文件
const chooseFile = () => {
	wx.chooseMessageFile({
		count: 1,
		type: 'file',
		success: (res) => {
			const file = res.tempFiles[0]
			selectedFile.value = {
				name: file.name,
				size: formatFileSize(file.size),
				path: file.path
			}
		}
	})
}

// 格式化文件大小
const formatFileSize = (size) => {
	if (size < 1024) {
		return size + 'B'
	} else if (size < 1024 * 1024) {
		return (size / 1024).toFixed(2) + 'KB'
	} else {
		return (size / (1024 * 1024)).toFixed(2) + 'MB'
	}
}

// 删除文件
const deleteFile = () => {
	selectedFile.value = null
}

// 表单验证
const validateForm = () => {
	if (!form.userId) {
		wx.showToast({
			title: '请选择谈话对象',
			icon: 'none'
		})
		return false
	}
	if (!form.talkTitle) {
		wx.showToast({
			title: '请输入谈话主题',
			icon: 'none'
		})
		return false
	}
	if (!form.talkTime) {
		wx.showToast({
			title: '请选择谈话时间',
			icon: 'none'
		})
		return false
	}
	if (!form.talkPlace) {
		wx.showToast({
			title: '请输入谈话地点',
			icon: 'none'
		})
		return false
	}
	if (!form.talkSummary) {
		wx.showToast({
			title: '请输入谈话摘要',
			icon: 'none'
		})
		return false
	}
	return true
}

// 提交表单
const submitForm = async () => {
	if (!validateForm()) return
	
	wx.showLoading({
		title: '提交中...'
	})
	
	try {
		// 如果有文件，先上传文件
		if (selectedFile.value) {
			form.fileUrl = await uploadFile(selectedFile.value.path)
		}
		
		form.applicantId = userId;
		// 提交表单
		const res = await submitTalkInfo(form);
		
		if (res.code === 200) {
			wx.showToast({
				title: '提交成功',
				icon: 'success'
			})
			setTimeout(() => {
				wx.navigateBack()
			}, 1500)
		} else {
			wx.showToast({
				title: res.message || '提交失败',
				icon: 'none'
			})
		}
	} catch (error) {
		wx.showToast({
			title: '网络错误',
			icon: 'none'
		})
	} finally {
		wx.hideLoading()
	}
}

// 生命周期钩子
onMounted(async () => {
	try {
		await initTimeArray()
		await getUserList()
	} finally {
		// 延迟一下再隐藏加载动画，让页面渲染更流畅
		setTimeout(() => {
			isLoading.value = false
		}, 300)
	}
})
</script>

<style lang="scss" scoped>
.container {
	padding: 30rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
	box-sizing: border-box;
	position: relative;
}

.loading {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 999;
}

.loading-spinner {
	width: 80rpx;
	height: 80rpx;
	border: 6rpx solid #f3f3f3;
	border-top: 6rpx solid #ff7a45;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.header {
	background-color: #fff;
	padding: 40rpx 30rpx;
	margin-bottom: 30rpx;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	
	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 16rpx;
	}
	
	.subtitle {
		font-size: 28rpx;
		color: #666;
	}
}

.form-container {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-item {
	margin-bottom: 40rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.label {
	font-size: 30rpx;
	color: #333;
	margin-bottom: 20rpx;
	font-weight: 500;
	
	&.required::before {
		content: '*';
		color: #ff7a45;
		margin-right: 4rpx;
	}
}

.input {
	width: 100%;
	height: 88rpx;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 0 24rpx;
	font-size: 30rpx;
	box-sizing: border-box;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.picker {
	width: 100%;
	height: 88rpx;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 0 24rpx;
	font-size: 30rpx;
	line-height: 88rpx;
	color: #333;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-sizing: border-box;
	
	.placeholder {
		color: #999;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.arrow {
		color: #999;
		font-size: 24rpx;
		transform: rotate(90deg);
		margin-left: 12rpx;
		flex-shrink: 0;
	}
}

.duration-container {
	display: flex;
	align-items: center;
}

.duration-btn {
	width: 72rpx;
	height: 72rpx;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 40rpx;
	color: #666;
	
	&:active {
		background-color: #eee;
	}
}

.duration-input {
	width: 120rpx;
	height: 72rpx;
	text-align: center;
	margin: 0 24rpx;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	font-size: 30rpx;
}

.duration-unit {
	margin-left: 24rpx;
	color: #666;
	font-size: 30rpx;
}

.textarea {
	width: 100%;
	height: 240rpx;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 24rpx;
	font-size: 30rpx;
	box-sizing: border-box;
	line-height: 1.5;
}

.word-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 12rpx;
	display: block;
}

.upload-container {
	margin-top: 20rpx;
}

.upload-list {
	display: flex;
	flex-direction: column;
}

.upload-item {
	width: 100%;
	height: 88rpx;
	margin-bottom: 20rpx;
	position: relative;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	padding: 0 24rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-sizing: border-box;
}

.file-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.file-name {
	font-size: 30rpx;
	color: #333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.file-size {
	font-size: 24rpx;
	color: #999;
	margin-top: 4rpx;
}

.delete-btn {
	width: 40rpx;
	height: 40rpx;
	background-color: rgba(0, 0, 0, 0.1);
	color: #666;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	margin-left: 20rpx;
	
	&:active {
		background-color: rgba(0, 0, 0, 0.2);
	}
}

.upload-btn {
	width: 100%;
	height: 88rpx;
	background-color: #f8f8f8;
	border-radius: 12rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	
	&:active {
		background-color: #eee;
	}
}

.upload-icon {
	font-size: 40rpx;
	color: #999;
	margin-bottom: 4rpx;
}

.upload-text {
	font-size: 28rpx;
	color: #999;
}

.submit-btn {
	margin-top: 60rpx;
	background-color: #ff7a45;
	height: 88rpx;
	line-height: 88rpx;
	font-size: 32rpx;
	border-radius: 44rpx;
	font-weight: 500;
	
	&:active {
		opacity: 0.9;
	}
}
</style> 